package com.alipay.app.groupmeal.standard.ui.b.function.mode;

import android.content.Context;
import android.util.AttributeSet;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alipay.app.groupmeal.standard.R;
import com.alipay.app.groupmeal.standard.constant.BaseConstant;
import com.alipay.app.groupmeal.standard.bean.ModeBean;
import com.alipay.app.groupmeal.standard.constant.ConfigConstant;
import com.alipay.app.groupmeal.standard.listener.OnMyItemClickListener;
import com.alipay.app.groupmeal.standard.ui.b.util.DeviceInfoManager;
import com.alipay.app.groupmeal.standard.widget.business.BScreenRecyclerView;
import com.alipay.app.groupmeal.standard.widget.business.BaseBScreenView;
import com.alipay.sdk.util.DeviceUtil;
import com.alipay.sdk.util.TextUtil;
import com.blankj.utilcode.util.SizeUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;

import java.util.ArrayList;
import java.util.List;

/**
 * @ProjectName: 团餐
 * @ClassName: BScreenModeSelect
 * @Description: 收银模式选择
 * @Author: bd-001935
 * @CreateDate: 4/19/22 9:05 PM
 * @UpdateUser: bd-001935
 * @UpdateDate: 4/19/22 9:05 PM
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class BScreenModeSelect extends BaseBScreenView {

    private BScreenRecyclerView mBsRecyclerView;
    private BScreenSetFixedAmountDialog mAmountDialog;
    private List<ModeBean> mList;
    private BaseQuickAdapter<ModeBean, BaseViewHolder> mAdapter;
    //当前获取焦点的下标
    private int mCurrentFocusPosition;
    private int mLastPosition;
    private int mItemHeight;
    private String mCashierMode;
    private Display mDisplay;
    private LinearLayout.LayoutParams mLayoutParams;
    private int fixedModePosition;
    private View mFocusView;

    public BScreenModeSelect(Context context) {
        this(context, null);
    }

    public BScreenModeSelect(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BScreenModeSelect(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected int getLayoutId() {
        if (ConfigConstant.displayType == BaseConstant.DISPLAY_TYPE.T2) {
            return R.layout.view_mode_list_ft2;
        } else {
            return R.layout.view_mode_list;
        }
    }

    @Override
    protected void initView(View view) {
        mBsRecyclerView = view.findViewById(R.id.bsRecyclerView);
        mAmountDialog = view.findViewById(R.id.amountDialog);
    }

    @Override
    protected void initData() {
        //计算item高度
        mBsRecyclerView.setFocusable(false);
        initAdapter();
        mAmountDialog.setSetting(true);
        mAmountDialog.setAmountConfirmListener(new BScreenSetFixedAmountDialog.AmountConfirmListener() {
            @Override
            public void onConfirm(String amount) {
                mAdapter.notifyItemChanged(fixedModePosition);
            }
        });
    }

    //显示适配器
    private void initAdapter() {
        mAdapter = new BaseQuickAdapter<ModeBean, BaseViewHolder>(R.layout.item_mode, mList) {
            @Override
            protected void convert(@NonNull BaseViewHolder baseViewHolder, ModeBean bean) {
                LinearLayout root = baseViewHolder.findView(R.id.ll_mode_root);
                //设置item高度
                root.setLayoutParams(mLayoutParams);
                baseViewHolder.setText(R.id.tv_mode_title, bean.title);
                baseViewHolder.setGone(R.id.tv_using, !bean.isUsing);
                baseViewHolder.setText(R.id.tv_desc, bean.desc);

                if (bean.mode.equals(mCashierMode)) {
                    if (mFocusView == null) {
                        root.requestFocus();
                    }
                    mFocusView = root;
                }
                //固定模式
                if (bean.mode.equals(BaseConstant.CASHIER_MODE.MODE_FIXED)) {
                    fixedModePosition = baseViewHolder.getLayoutPosition();
                    if (DeviceInfoManager.haveSetAmount()) {
                        //已经设置金额
                        baseViewHolder.setGone(R.id.tv_desc, true);
                        baseViewHolder.setGone(R.id.tv_amount, false);
                        baseViewHolder.setText(R.id.tv_amount, TextUtil.formatPrice(DeviceInfoManager.getFixedAmount()));
                    } else {
                        //没有设置金额
                        baseViewHolder.setGone(R.id.tv_desc, false);
                        baseViewHolder.setGone(R.id.tv_amount, true);
                    }
                }
                if (root.isFocused())
                    setFocusUI(baseViewHolder, bean);
                else
                    setDefaultUI(baseViewHolder);
                root.setOnFocusChangeListener((v, hasFocus) -> {
                    if (hasFocus) {
                        mLastPosition = mCurrentFocusPosition;
                        mCurrentFocusPosition = baseViewHolder.getLayoutPosition();
                        setFocusUI(baseViewHolder, bean);
                    } else {
                        setDefaultUI(baseViewHolder);
                    }
                });
            }
        };


        mBsRecyclerView.setAdapter(mAdapter);
        mBsRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL, false));
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (mOnMyItemClickListener != null)
                    mOnMyItemClickListener.onItemClick(adapter, view, position);
            }
        });
    }

    private void setFocusUI(BaseViewHolder baseViewHolder, ModeBean bean) {
        baseViewHolder.setTextColor(R.id.tv_mode_title, getContext().getColor(R.color.white));
        baseViewHolder.setTextColor(R.id.tv_using, getContext().getColor(R.color.txt_333333));
        baseViewHolder.setBackgroundResource(R.id.tv_using, R.drawable.bg_mode_using_focus);
        baseViewHolder.setTextColor(R.id.tv_desc, getContext().getColor(R.color.txt_A5CCFF));
        baseViewHolder.setGone(R.id.actionButton, !mCashierMode.equals(BaseConstant.CASHIER_MODE.MODE_FIXED) ||
                !bean.mode.equals(BaseConstant.CASHIER_MODE.MODE_FIXED));
        baseViewHolder.setTextColor(R.id.tv_amount, getContext().getColor(R.color.txt_1677FF));
    }

    private void setDefaultUI(BaseViewHolder baseViewHolder) {
        baseViewHolder.setTextColor(R.id.tv_mode_title, getContext().getColor(R.color.txt_333333));
        baseViewHolder.setTextColor(R.id.tv_using, getContext().getColor(R.color.white));
        baseViewHolder.setBackgroundResource(R.id.tv_using, R.drawable.bg_mode_using);
        baseViewHolder.setTextColor(R.id.tv_desc, getContext().getColor(R.color.txt_666666));
        baseViewHolder.setGone(R.id.actionButton, true);
        baseViewHolder.setTextColor(R.id.tv_amount, getResources().getColor(R.color.txt_666666));
    }

    private OnMyItemClickListener mOnMyItemClickListener;

    public void setOnMyItemClickListener(OnMyItemClickListener onMyItemClickListener) {
        mOnMyItemClickListener = onMyItemClickListener;
    }

    public void setData(Display display, int statusBarHeight) {
        mDisplay = display;
        mLastPosition = -1;
        mCashierMode = DeviceInfoManager.getCashierMode();
        if (mList == null) {
            mList = new ArrayList<>();
            ModeBean modeBean = new ModeBean();
            modeBean.title = "自由模式";
            modeBean.desc = "手动输入金额";
            modeBean.mode = BaseConstant.CASHIER_MODE.MODE_FREE;
            mList.add(modeBean);

            modeBean = new ModeBean();
            modeBean.title = "固定模式";
            modeBean.desc = "以固定金额收银";
            modeBean.mode = BaseConstant.CASHIER_MODE.MODE_FIXED;
            mList.add(modeBean);

            modeBean = new ModeBean();
            modeBean.title = "核销模式";
            modeBean.desc = "手机订餐现场领取";
            modeBean.mode = BaseConstant.CASHIER_MODE.MODE_HEXIAO;
            mList.add(modeBean);

            //判断模式是否被选择上，显示使用中
            for (int i = 0; i < mList.size(); i++) {
                if (mList.get(i).mode.equals(mCashierMode)) {
                    mList.get(i).isUsing = true;
                    mCurrentFocusPosition = i;
                } else
                    mList.get(i).isUsing = false;
            }
        }

        mItemHeight = (DeviceUtil.getScreenHeight(mDisplay) -
                statusBarHeight -
                SizeUtils.dp2px(30) * 2 -
                SizeUtils.dp2px(14)) / 3;

        //设置item高度
        mLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, mItemHeight);
        mLayoutParams.setMargins(0, SizeUtils.dp2px(7), 0, SizeUtils.dp2px(7));
        if (mFocusView == null) {
            mAdapter.setList(mList);
        }
        if (mFocusView != null)
            mFocusView.requestFocus();
        setVisibility(VISIBLE);
    }

    public void changeMode() {
        if (mAdapter.getData() != null) {
//            if (mCurrentPosition == mLastPosition) {
//                return;
//            }
            //刷新UI
            for (int i = 0; i < mList.size(); i++) {
                if (mList.get(i).mode.equals(mCashierMode)) {
                    mList.get(i).isUsing = true;
                } else {
                    mList.get(i).isUsing = false;
                }
                mAdapter.notifyItemChanged(i);
            }
            mAdapter.notifyItemChanged(mLastPosition);
            mAdapter.notifyItemChanged(mCurrentFocusPosition);
        }

        //提前更新functionView中视图
        if (mOnModeSelectListener != null) {
            mOnModeSelectListener.onChange();
        }
    }

    @Override
    public boolean onKeyEventEnter(KeyEvent event) {
        System.out.println("测试");
        if (mAdapter.getData() != null) {
            if (mAmountDialog != null && mAmountDialog.isVisibility()) {
                return mAmountDialog.onKeyEventEnter(event);
            }

            if (mAdapter.getData().get(mCurrentFocusPosition).mode.equals(BaseConstant.CASHIER_MODE.MODE_FREE)) {
                mCashierMode = mAdapter.getItem(mCurrentFocusPosition).mode;
                //保存到sp
                DeviceInfoManager.setCashierMode(mCashierMode);
                //非固定模式,选中就保存
                changeMode();
            } else if (mAdapter.getData().get(mCurrentFocusPosition).mode.equals(BaseConstant.CASHIER_MODE.MODE_HEXIAO)) {
                mCashierMode = mAdapter.getItem(mCurrentFocusPosition).mode;
                DeviceInfoManager.setCashierMode(mCashierMode);
                changeMode();
            } else {
                //固定模式,设置金额
                if (mCashierMode.equals(BaseConstant.CASHIER_MODE.MODE_FIXED)) {
                    //已选中的,设置金额
                    mAmountDialog.setVisibility(VISIBLE);
                } else {
                    if (!DeviceInfoManager.haveSetAmount()) {
                        //没有设置过金额,需要先设置金额
                        mAmountDialog.setVisibility(VISIBLE);
                    } else {
                        mCashierMode = mAdapter.getItem(mCurrentFocusPosition).mode;
                        //保存到sp
                        DeviceInfoManager.setCashierMode(mCashierMode);
                        //设置过金额的,先选中模式
                        changeMode();
                    }
                }
            }
        }

        return super.onKeyEventEnter(event);
    }

    @Override
    public boolean onKeyEventNum(KeyEvent event) {
        if (mAmountDialog != null && mAmountDialog.isVisibility()) {
            return mAmountDialog.dispatchKeyEvent(event);
        }
        return super.onKeyEventNum(event);
    }

    @Override
    public boolean onKeyEventBack(KeyEvent event) {
        if (mAmountDialog != null && mAmountDialog.isVisibility()) {
            mAmountDialog.dismiss();
            return false;
        } else {
            dismiss();
            //关闭收银模式
            if (mOnModeSelectListener != null)
                mOnModeSelectListener.onBackKey();
        }
        return super.onKeyEventBack(event);
    }

    @Override
    public boolean onKeyEventUpAndDown(KeyEvent event) {
        if (mAmountDialog != null && mAmountDialog.isVisibility())
            return false;
        return super.onKeyEventUpAndDown(event);
    }

    public interface OnModeSelectListener {
        void onChange();

        void onBackKey();
    }

    private OnModeSelectListener mOnModeSelectListener;

    public void setOnModeSelectListener(OnModeSelectListener onModeSelectListener) {
        mOnModeSelectListener = onModeSelectListener;
    }
}
